var fd;
/**
 *代理商申请表单组件
 */
var AgentApplyPanel = React.createClass({
    newAgentApply:function(){
        var imgs = [];
        var companyName = $('#companyName').val();
        var position = $('#position').val();
        var contact = $('#contact').val();
        var phone = $('#phone').val();
        var email = $('#email').val();
        var introducer = $('#introducer').val();
        var imgUploader = this.refs.imgUploader;
        var imgNames = imgUploader.state.imgs;
        for(var i in imgNames){
            var tmp = imgNames[i];
            imgs.push(tmp.name);
        }
        if(companyName == null || companyName == ''){
            layer.msg('公司名称不能为空');
            return;
        }else if(position == null || position == ''){
            layer.msg('申请人职位不能为空');
            return;
        }else if(contact == null || contact == ''){
            layer.msg('申请人姓名不能为空');
            return;
        }else if(phone == null || !checkMobile(phone)){
            layer.msg('电话为空或电话格式不正确');
            return;
        }else if(email == null || !isEmail(email)){
            layer.msg('邮箱为空或邮箱格式不正确');
            return;
        }else if(imgs.length == 0){
            layer.msg('公司资质不能为空');
            return;
        }
        $.ajax({
            url:CTX_PATH+'/apply/new/agent/apply',
            type:'post',
            traditional :true,
            data:{
                token:$.cookie('token'),
                companyName:companyName,
                position:position,
                contact:contact,
                phone:phone,
                email:email,
                introducer:introducer,
                imgs:imgs
            },
            success:function(rtn){
                console.log('agentApply data:%o',rtn);
                if(!rtn.error){
                    layer.msg('提交成功,请您耐心等待管理员审核！');
                    window.location.href = CTX_PATH+'/home';
                }else{
                    layer.msg('提交失败'+rtn.msg+'('+rtn.error+')');
                }
            }
            
        });
    },
	render:function(){
	    var phone = this.props.phone;
	    var email = this.props.email;
		return <div className='col-md-8 column'>
				    <form id='agent'>
					    <div className='field-box'>
					    	<span className='input-request-info'>*</span>	
					        <label>公司名称:</label>
					        <div className='col-md-5'>
					        	<input className='form-control' id='companyName' type='text'/>
					        </div>
					    </div>     
					    <div className='field-box'>
					    	<span className='input-request-info'>*</span>
					        <label>申请人职位:</label>
					        <div className='col-md-5'>
					        	<input className='form-control' id='position' type='text'/>
					        </div>
					    </div>
					    <div className='field-box'>
					    	<span className='input-request-info'>*</span>
					        <label>申请人姓名:</label>
					        <div className='col-md-5'>
					        	<input className='form-control' type='text' id='contact'/>
					        </div>
					    </div>
					    <div className='field-box'>
					    	<span className='input-request-info'>*</span>
					    	<label>联系电话:</label>
					        <div className='col-md-5'>
					        	<input className='form-control' type='text' id='phone' defaultValue={phone}/>
					        </div>
					    </div>
					    <div className='field-box'>
					    	<span className='input-request-info'>*</span>
					        <label>邮箱:</label>
					        <div className='col-md-5'>
					        	<input className='form-control' type='text' id='email' defaultValue={email}/>
					        </div>
					    </div>
					    <div className='field-box'>
					        <label>太易介绍人:</label>
					        <div className='col-md-5'>
					        	<input className='form-control' type='text' id='introducer'/>
					        </div>
					    </div>
					    <div className='field-box'>
					    	<span className='input-request-info'>*</span>
					    	<label>公司资质(营业执照):</label>
					    	<ImgUploader ref='imgUploader'  uploadUrl={CTX_PATH+'/apply/img/upload'} delUrl={CTX_PATH+'/apply/del/img'}/>
					    </div>
					    <div className='btn-submit'>
					    	<input type='button' className='btn-glow primary' id='btn-submit' value='提交' onClick={this.newAgentApply}/>
					    </div>
				</form>
			</div>
	}
});
function initAgentApply(){
    loadUserData();
}
	
/**
 * 
 */
var ImgUploader = React.createClass({
    getInitialState: function() {
        var imgs = [];
        if(this.props.imgs != null){
            imgs = this.props.imgs;
        }
        return {imgs: imgs};
    },
    removeHandle:function(name){
        var stateImgs = this.state.imgs;
        var newImgs = [];
        for(var i in stateImgs){
            var tmp = stateImgs[i];
            if(tmp.name != name){
                newImgs.push(tmp);
            }else{
                $.ajax({
                    type: "post",
                    url: this.props.delUrl,
                    data: {
                        imgName:tmp.name 
                    },
                    success: function(rtn) {
                        console.log(rtn);
                        if(!rtn.error){
                            layer.msg('图片删除"'+name+'"成功');
                        }else{
                            layer.msg('图片删除"'+name+'"失败');
                            console.error(rtn.error)
                        }
                    }
                });
            }
            
        }
        this.setState({
            imgs:newImgs
        })
    },
    upload:function(name,data){
        var imgs = this.state.imgs;
        $.ajax({
            type: "post",
            url: this.props.uploadUrl,
            async: true,
            data: data,
            processData: false,
            contentType: false,
            success: function(rtn) {
                console.log(rtn);
                if(!rtn.error){
                    var data = rtn.data;
                    for(var i in imgs){
                        var tmp = imgs[i];
                        if(tmp.name == name){
                            tmp.name = data[0];
                        }
                    }
                }else{
                    layer.msg('上传图片"'+name+'"失败');
                    console.error(rtn.error)
                }
            }
        });
        
    },
    addHandle:function(){
        var formName = 'file';
        fd = new FormData();
        var file = this.refs.file;
        var fileList = file.files; //获取的图片文件
        fileList = this.validate(fileList);
        var imgs = this.state.imgs;
        var length = imgs.length;
        var totalNum = length + fileList.length;
        
        if(fileList.length > 1){
            layer.msg('一次只能上传一张图片，多余图片被丢弃');
        }else if(totalNum <=5){
            var img = {};
            img.name = fileList[0].name;
            img.src= window.URL.createObjectURL(fileList[0]);
            imgs.push(img);
            fd.append(formName,fileList[0]);
            console.log(fileList[0])
            this.upload(img.name,fd);
            this.setState({
                imgs:imgs
            })
        }else{
            layer.msg('图片上传的上限为5张！无法继续上传');
        }
    },
    addButtonStyle:{
       width: '120px',
       height: '120px'
    },
    validate:function(files){
        var defaults = {
                fileType : ['jpg','png','bmp','jpeg'],   // 上传文件的类型
                fileSize : 1024 * 1024 * 5                 // 上传文件的大小 5M
        };
        var arrFiles = [];//替换的文件数组
        for(var i = 0, file; file = files[i]; i++){
            //获取文件上传的后缀名
            var newStr = file.name.split('').reverse().join('');
            if(newStr.split('.')[0] != null){
                    var type = newStr.split('.')[0].split('').reverse().join('');
                    if(jQuery.inArray(type, defaults.fileType) > -1){
                        // 类型符合，可以上传
                        if (file.size >= defaults.fileSize) {
                            alert(file.size);
                            alert('您这个"'+ file.name +'"文件大小过大');    
                        } else {
                            // 在这里需要判断当前所有文件中
                            arrFiles.push(file);    
                        }
                    }else{
                        alert('您这个"'+ file.name +'"上传类型不符合');   
                    }
                }else{
                    alert('您这个"'+ file.name +'"没有类型, 无法识别');    
                }
        }
        return arrFiles;
    },
    render:function(){
        var imgs = [];
        var stateImgs = this.state.imgs;
        for(var i in stateImgs){
            var tmp = stateImgs[i];
            imgs.push(<section className='up-section fl'>
                        <span className='up-span'></span>
                        <img className='close-upimg' src='/teops/img/a7.png' onClick={this.removeHandle.bind(this,tmp.name)}/>
                        <img className='up-img' src={tmp.src}/>
                        <p className='img-name-p'>{tmp.name}</p>
                        
                    </section>)
        }
        return (<div className='z_photo upimg-div clear'>
                {imgs}
                <section className='z_file fl'>
                    <img src='/teops/img/a11.png' style={this.addButtonStyle} onClick={this.add}/>
                    <input ref='file' type='file' className='file' accept='image/jpg,image/jpeg,image/png,image/bmp' multiple='' onChange={this.addHandle} />
                </section>
                </div>);
        
    }
});
function loadUserData(){
    $.ajax({
        url:CTX_PATH+'/apply/query/user/info',
        type:'post',
        traditional :true,
        data:{
            token:$.cookie('token')
        },
        success:function(rtn){
            console.log('userInfo data:%o',rtn);
            if(!rtn.error){
                var data = rtn.data;
                ReactDOM.render(
                    <AgentApplyPanel  phone = {data.phone} email = {data.email}></AgentApplyPanel>,
                    document.getElementById('agent-apply')
                );
            }else{
                layer.msg(rtn.msg+'('+rtn.error+')');
            }
        }
        
    });
    
}

/**
 * 邮箱验证
 */
function isEmail(str){
    var reg=/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/;
    return reg.test(str);
}

/**
 * 手机号验证
 */
function checkMobile(str) {
    var reg = /^1\d{10}$/;
    return reg.test(str);   
}

initAgentApply();